import copy from "copy-to-clipboard"
import React, { ReactElement } from "react"

interface CopyToClipboardProps {
    text: string
    onCopy?: (text: string, result: boolean) => void
    children: ReactElement
    options?: {
        debug?: boolean
        message?: string
        format?: string
    }
}

const CopyToClipboard: React.FC<CopyToClipboardProps> = (props) => {
    const {
        text,
        onCopy,
        children,
        options
    } = props;

    // React.Children.only 是用来断言 children 只有一个元素，如果不是就报错
    const ele = React.Children.only(children)
    function onClick(event: MouseEvent) {
        const elem = React.Children.only(children);
        const result = copy(text, options)
        if (onCopy) {
            onCopy(text, result);
        }

        if (typeof elem?.props?.onClick === 'function') {
            elem.props.onClick(event);
        }
    }
    return React.cloneElement(ele, { onClick })

}

export function TestCopyToClipboard() {
    return <CopyToClipboard text="abin  is good" onCopy={() => console.log('done')}>
        <div onClick={() => alert(111)}>aaaa</div>
    </CopyToClipboard>
}